<template>
  <div class="accountee-party">
    <div
      v-for="(item, index) in checkedBillReceiver"
      :key="item.index"
      class="sale-billReceiver-div"
    >
      <el-select
        v-model="item.billReceiver"
        filterable
        remote
        reserve-keyword
        :placeholder="parameter.promptTemplate"
        :remote-method="(arg) => remoteMethod(arg, undefined, index)"
        :loading="loading"
        value-key="code"
        style="flex: 1"
        clearable
        :disabled="readonly"
        @change="changeData(index)"
        @clear="remoteMethod('', 'clear', index)"
      >
        <el-option
          v-for="item in item.billReceiverList"
          :key="item.code"
          :label="item.code + item.fullName"
          :value="item"
        >
        </el-option>
      </el-select>
      <i
        v-if="index !== 0"
        class="el-icon-remove"
        @click="deletebillReceiver(index)"
      ></i>
    </div>
    <div v-if="detail.templateTypeCode === 'TMSHZ'">
      <el-button
        type="text"
        icon="el-icon-circle-plus"
        @click="addNewbillReceiver"
        >{{ $t('新增') }}</el-button
      >
    </div>
  </div>
</template>
<script>
/**
 *  http://wiki.zczy56.com/pages/viewpage.action?pageId=50341610  客户
    http://wiki.zczy56.com/pages/viewpage.action?pageId=50346399 内部公司 tms的签约主体， wms的签约主体
    http://172.20.21.211:8000/#/view/m8wJ0eN2                租户下内部用户接口
 */
import masertDataService from '@/services/masertDataService'
import eventBus from '@/assets/utils/eventBus.js'
export default {
  name: 'billReceiver',
  props: {
    detail: {
      typr: Object,
      default: () => {
        return {}
      },
    },
    value: [Object, String, Array],
    disabled: Boolean,
    parameter: {
      typr: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      checkedData: {},
      loading: false,
      readonly: false,
      checkedBillReceiver: [
        {
          index: new Date().getTime(),
          billReceiver: {},
          billReceiverList: [],
        },
      ],

      rules: {
        billReceiver: [
          {
            required: this.parameter.state === 4,
            validator: (rule, value, callback) => {
              if (this.parameter.state != 4 && this.parameter.fillFlag != 0) {
                callback()
                return
              }
              if (
                this.checkedBillReceiver.length > 0 &&
                this.checkedBillReceiver[0].billReceiver.code
              ) {
                callback()
              } else {
                callback(new Error(this.$t('请选择收票方')))
                return
              }
            },
            trigger: 'change',
            type: 'array',
          },
        ],
      },
    }
  },
  created() {
    let vm = this
    if (this.value) {
      this.checkedData = JSON.parse(this.value)
      this.checkedBillReceiver = this.checkedData.map((it) => {
        this.remoteMethod(it.code)
        return {
          index: new Date().getTime(),
          billReceiver: it,
          billReceiverList: [],
        }
      })
      this.changeData()
    } else {
      this.remoteMethod()
    }
    //接收客户主数据的第一次添加
    eventBus.$on('masterChange', (parameter, data) => {
      //必须是抬头信息的塞到抬头信息里面，支付条款的塞到支付条款里面
      if (
        !parameter.parameterPosition ||
        parameter.parameterPosition !== vm.parameter.parameterPosition
      ) {
        return
      }
      let noValue =
        !vm.checkedBillReceiver ||
        !vm.checkedBillReceiver.length ||
        (vm.checkedBillReceiver.length > 0 &&
          !vm.checkedBillReceiver[0].billReceiver.code)
      if (
        noValue &&
        (parameter.parameterNumber === 'signTarget' ||
          parameter.parameterNumber === 'signSubject')
      ) {
        let templateTypeCode = vm.detail.templateTypeCode
        if (
          templateTypeCode === 'TMSHZ' ||
          templateTypeCode === 'WMSHZ2' ||
          templateTypeCode === 'WMSHZ1'
        ) {
          if (parameter.parameterNumber === 'signTarget') {
            vm.checkedBillReceiver = [
              {
                index: new Date().getTime(),
                billReceiver: data,
                billReceiverList: [data],
              },
            ]

            eventBus.$emit(
              'changeaccount',
              this.parameter,
              this.checkedAccounteeParty
            )
          }
        } else {
          if (parameter.parameterNumber === 'signSubject') {
            vm.checkedBillReceiver = [
              {
                index: new Date().getTime(),
                billReceiver: data,
                billReceiverList: [data],
              },
            ]

            eventBus.$emit(
              'changeaccount',
              this.parameter,
              this.checkedAccounteeParty
            )
          }
        }
      }
    })
    this.readonly = Boolean(this.$route.query.readonly) || this.disabled
    this.$emit('setrules', this.parameter, {
      [this.parameter.parameterNumber]: this.rules.billReceiver,
    })
  },
  methods: {
    remoteMethod(query, type, index) {
      //多式联运货主
      let kind = []
      let templateTypeCode = this.detail.templateTypeCode
      let systemFlag = null
      switch (templateTypeCode) {
        case 'TMSHZ': //多式联运货主
          kind = [1, 2]
          systemFlag = 1
          break
        case 'TMSCYS': //多式联运承运商
          kind = [3]
          systemFlag = 1
          break
        case 'TMSSJ': //多式联运个体司机
          kind = [4]
          systemFlag = 1
          break
        case 'TMSCLB': //多式联运车老板
          kind = [5]
          systemFlag = 1
          break
        case 'WMSHZ1': //仓储货主（通用）
          kind = [6]
          systemFlag = 2
          break
        case 'WMSHZ2': //仓储货主（行业）
          kind = [6]
          systemFlag = 2
          break
      }
      if (type === 'clear') {
        this.checkedBillReceiver[index].billReceiverList = []
        eventBus.$emit('billreceiver', this.changeData, index)
      } else {
        //只有TMS多式联运货主和wms的模板调客户接口，其他的调签约主体的接口
        if (
          templateTypeCode === 'TMSHZ' ||
          templateTypeCode === 'WMSHZ2' ||
          templateTypeCode === 'WMSHZ1'
        ) {
          this.remoteSignTarget(query, kind, index)
        } else {
          this.remoteSignSubject(query, systemFlag, index)
        }
      }
    },
    remoteSignTarget(query, kind, index) {
      let vm = this
      masertDataService
        .findSaasAllCustomerList({
          kind: kind, //Tms: 1、货主  2、托运商  3、分供方,4 司机 5车老板(tms); wms: 6 wms货主(wms)
          status: [1],
          codeOrNameLike: query,
          dataPerFlag: 1,
        })
        .then((res) => {
          this.checkedBillReceiver.forEach((it, i) => {
            if (it.billReceiver.code === query || index == i) {
              it.billReceiverList = res.data
            }
          })
        })
    },
    remoteSignSubject(query, systemFlag, index) {
      masertDataService
        .findSaasAllCompanyList({
          state: 1,
          // systemFlag: systemFlag, //运输:1.运输,2.仓储,3.园区,4.商贸,5.核算系统,6.金融,7.价格中心,8.网货
          systemFlag: null,
          skipPrdFlag: 1, // 1不限产品范围  其他限制
          codeOrNameLike: query,
          tenantCode: localStorage.getItem('tenantCode'),
        })
        .then((res) => {
          this.checkedBillReceiver.forEach((it, i) => {
            if (it.billReceiver.code === query || index == i) {
              it.billReceiverList = res.data.map((it) => {
                return {
                  ...it,
                  code: it.companyCode,
                  name: it.companyName,
                  fullName: it.companyFullName,
                }
              })
            }
          })
        })
    },
    changeData(index) {
      this.$emit('input', this.checkedBillReceiver)
      eventBus.$emit('billreceiver', this.checkedBillReceiver, index)
    },
    getData() {
      return this.checkedBillReceiver.map((it) => {
        return {
          code: it.billReceiver.code,
          name: it.billReceiver.name,
          fullName: it.billReceiver.fullName,
        }
      })
    },
    addNewbillReceiver() {
      this.checkedBillReceiver.push({
        index: new Date().getTime(),
        billReceiver: {},
        billReceiverList: [],
      })
    },
    deletebillReceiver(index) {
      this.checkedBillReceiver.splice(index, 1)
      eventBus.$emit('changebillreceiver', this.changeData, index)
    },
  },
}
</script>
<style lang="scss">
.sale-billReceiver-div {
  display: flex;
  margin-bottom: 12px;
  .el-icon-remove {
    font-size: 24px;
    cursor: pointer;
    align-self: center;
    margin-left: 8px;
  }
  &:last-child {
    margin-bottom: 0px;
  }
}
</style>
